package com.dayuanit.dy17.atm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dayuanit.dy17.atm.dto.ResponseDTO;
import com.dayuanit.dy17.atm.entity.User;
import com.dayuanit.dy17.atm.entity.WxBind;
import com.dayuanit.dy17.atm.service.IUserService;
import com.dayuanit.dy17.atm.util.ApiConnector;
import com.dayuanit.dy17.oauth.wx.WxAccessTokenDomain;
import com.dayuanit.dy17.oauth.wx.WxLoginHandler;
import com.dayuanit.dy17.oauth.wx.WxUserInfoDomain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class WxController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private WxLoginHandler wxLoginHandler;

    @RequestMapping(value = "/wx/createCodeUrl")
    @ResponseBody
    public ResponseDTO createCodeUrl() {
        return ResponseDTO.success(wxLoginHandler.getCodeUrl());
    }

    @RequestMapping(value = "/wx/wxLoginCallback")
    public String wxLoginCallback(String code, HttpServletRequest req, HttpSession session) {
        System.out.println("code=" + code);

        // 发送获取accessToken请求
        WxAccessTokenDomain wxAccessTokenDomain = wxLoginHandler.getAccessToken(code);

        // 通过openID 查看此微信账号是否绑定，若绑定则将用户信息放在session中
        WxBind wxbind = userService.getWxbind(wxAccessTokenDomain.getOpenid());
        if (null != wxbind) {
            User user = userService.getUser(wxbind.getUserId());
            session.setAttribute(login_user, user);
            return "redirect:/user/toHome.do";
        }

        // 第三步  获取用户信息
        WxUserInfoDomain wxUserInfo = wxLoginHandler.getWxUserInfo(wxAccessTokenDomain);
        session.setAttribute("wxUserInfo", wxUserInfo);

        // 去绑定页面
        return "redirect:/wx/toWxBind.do";
    }

    @RequestMapping(value = "/wx/wxLoginBind", method = RequestMethod.POST)
    @ResponseBody
    public ResponseDTO wxLoginBind(String username, String password, HttpSession session) {
        WxUserInfoDomain wxUserInfo = (WxUserInfoDomain)session.getAttribute("wxUserInfo");

        userService.wxLoginBind(username, password, wxUserInfo);
        return ResponseDTO.success();
    }
}
